/**
 * Zendesk Widget 工具类
 * 用于管理Zendesk聊天机器人的初始化和交互
 */

/**
 * 检查Zendesk Widget是否已加载
 */
export const isZendeskLoaded = () => {
  return typeof window.zE !== 'undefined'
}

/**
 * 等待Zendesk Widget加载完成
 * @param {number} timeout - 超时时间(毫秒)
 * @param {number} interval - 检查间隔(毫秒)
 * @returns {Promise<boolean>}
 */
export const waitForZendesk = (timeout = 5000, interval = 100) => {
  return new Promise((resolve) => {
    const startTime = Date.now()
    
    const checkZendesk = () => {
      if (isZendeskLoaded()) {
        resolve(true)
      } else if (Date.now() - startTime > timeout) {
        resolve(false)
      } else {
        setTimeout(checkZendesk, interval)
      }
    }
    
    checkZendesk()
  })
}

/**
 * 设置Zendesk语言
 * @param {string} lang - 语言代码 'zh' 或 'en'
 */
export const setZendeskLocale = (lang) => {
  if (!isZendeskLoaded()) return
  
  try {
    const locale = lang === 'zh' ? 'zh-cn' : 'en-us'
    // Zendesk Messenger API
    window.zE('messenger:set', 'locale', locale)
  } catch (error) {
    console.warn('Failed to set Zendesk locale:', error)
  }
}

/**
 * 打开Zendesk聊天窗口
 * @returns {Promise<boolean>} - 是否成功打开
 */
export const openZendeskChat = async () => {
  if (isZendeskLoaded()) {
    try {
      // 添加body类名以显示Zendesk
      document.body.classList.add('zendesk-visible')
      // Zendesk Web Widget API - 直接打开
      window.zE('messenger', 'open')
      return true
    } catch (error) {
      console.error('Failed to open Zendesk:', error)
      document.body.classList.remove('zendesk-visible')
      return false
    }
  }
  
  // 等待Zendesk加载
  const loaded = await waitForZendesk()
  if (loaded) {
    try {
      // 添加body类名以显示Zendesk
      document.body.classList.add('zendesk-visible')
      // Zendesk Web Widget API - 直接打开
      window.zE('messenger', 'open')
      return true
    } catch (error) {
      console.error('Failed to open Zendesk:', error)
      document.body.classList.remove('zendesk-visible')
      return false
    }
  }
  
  return false
}

/**
 * 关闭Zendesk聊天窗口
 */
export const closeZendeskChat = () => {
  if (!isZendeskLoaded()) return
  try {
    window.zE('messenger', 'close')
    // 移除body类名
    document.body.classList.remove('zendesk-visible')
  } catch (error) {
    console.warn('Failed to close Zendesk:', error)
    // 即使失败也要移除类名
    document.body.classList.remove('zendesk-visible')
  }
}

/**
 * 显示Zendesk Widget
 */
export const showZendeskWidget = () => {
  if (!isZendeskLoaded()) return
  try {
    window.zE('messenger', 'show')
  } catch (error) {
    console.warn('Failed to show Zendesk:', error)
  }
}

/**
 * 隐藏Zendesk Widget
 */
export const hideZendeskWidget = () => {
  if (!isZendeskLoaded()) return
  try {
    window.zE('messenger', 'hide')
  } catch (error) {
    console.warn('Failed to hide Zendesk:', error)
  }
}

/**
 * 设置用户信息
 * @param {Object} userInfo - 用户信息
 * @param {string} userInfo.name - 用户名
 * @param {string} userInfo.email - 用户邮箱
 * @param {string} userInfo.phone - 用户手机号
 */
export const setZendeskUser = (userInfo) => {
  if (!isZendeskLoaded()) return
  
  const { name, email, phone } = userInfo
  
  if (name) {
    window.zE('messenger', 'loginUser', function(callback) {
      callback({
        name: name,
        email: email || '',
        phone: phone || ''
      })
    })
  }
}

/**
 * 发送自定义事件
 * @param {string} eventName - 事件名称
 * @param {Object} eventData - 事件数据
 */
export const trackZendeskEvent = (eventName, eventData = {}) => {
  if (!isZendeskLoaded()) return
  
  window.zE('messenger', 'track', eventName, eventData)
}

/**
 * 预填充消息
 * @param {string} message - 预填充的消息内容
 */
export const prefillZendeskMessage = (message) => {
  if (!isZendeskLoaded()) return
  
  window.zE('messenger', 'prefill', {
    message: {
      text: message
    }
  })
}

/**
 * 初始化Zendesk Widget
 * @param {Object} options - 初始化选项
 * @param {string} options.lang - 语言代码
 * @param {Object} options.user - 用户信息
 */
export const initZendesk = async (options = {}) => {
  const { lang = 'zh', user = null } = options
  
  // 等待Zendesk加载
  const loaded = await waitForZendesk()
  
  if (!loaded) {
    console.warn('Zendesk Widget failed to load')
    return false
  }
  
  // 设置语言
  setZendeskLocale(lang)
  
  // 设置用户信息
  if (user) {
    setZendeskUser(user)
  }
  
  // 监听Zendesk关闭事件
  try {
    window.zE('messenger:on', 'close', () => {
      // 当用户点击关闭按钮时,自动移除类名
      document.body.classList.remove('zendesk-visible')
    })
  } catch (error) {
    console.warn('Failed to set Zendesk close listener:', error)
  }
  
  return true
}

export default {
  isZendeskLoaded,
  waitForZendesk,
  setZendeskLocale,
  openZendeskChat,
  closeZendeskChat,
  showZendeskWidget,
  hideZendeskWidget,
  setZendeskUser,
  trackZendeskEvent,
  prefillZendeskMessage,
  initZendesk
}

